﻿using JiebaNet.Segmenter;
using JiebaNet.Segmenter.Common;
using JiebaNet.Segmenter.FinalSeg;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Application.Common.Utils
{
    public class JieBaHelper
    {
    }
    public class JieBa
    {

        internal static readonly Regex RegexChineseCutAll = new Regex("([\\u4E00-\\u9FD5]+)", RegexOptions.Compiled);
        public IEnumerable<string> LoadStopWord(string fullPath)
        {
            List<string> res = new();
            try
            {
                string[] array = File.ReadAllLines(fullPath, Encoding.UTF8);
                foreach (string text in array)
                {
                    if (!string.IsNullOrWhiteSpace(text))
                    {
                        res.Add(text);
                    }
                }
                return res;
            }
            catch (IOException)
            {
            }
            catch (FormatException)
            {
            }
            return res;

        }

        public Dictionary<string, int> Cut(string text)
        {
            var res = new Dictionary<string, int>();
            var jieba = new JiebaSegmenter();

            var basePath = System.AppDomain.CurrentDomain.BaseDirectory;
            var dictPath = Path.Combine(Path.Combine(basePath, "Resources"), "dict.txt");
            jieba.LoadUserDict(dictPath);
            var stopPath = Path.Combine(Path.Combine(basePath, "Resources"), "stopwords.txt");
            var stopList = LoadStopWord(stopPath);


            var cut = jieba.Cut(text,true);
            if (cut != null)
            {
                foreach (var c in cut)
                {
                    if (stopList.Contains(c))
                        continue;
                    if (res.ContainsKey(c))
                    {
                        res[c] += 1;
                    }
                    else
                    {
                        res.Add(c, 1);
                    }
                }
            }
            return res;
        }

        public int GetDistance(ulong value1,string value2)
        {
            ulong.TryParse(value2, out var rValue2);

            ulong x = (rValue2 ^ value1) & (ulong.MaxValue);
            int ans = 0;
            while (x > 0)
            {
                ans++;
                if (ans > 3) return 4;
                x &= x - 1;
            }
            return ans;
        }


    }
}
